var fs ;

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

function errorHandler(e) {
  var msg = '';

  switch (e.code) {
    case FileError.QUOTA_EXCEEDED_ERR:
      msg = 'QUOTA_EXCEEDED_ERR';
      break;
    case FileError.NOT_FOUND_ERR:
      msg = 'NOT_FOUND_ERR';
      break;
    case FileError.SECURITY_ERR:
      msg = 'SECURITY_ERR';
      break;
    case FileError.INVALID_MODIFICATION_ERR:
      msg = 'INVALID_MODIFICATION_ERR';
      break;
    case FileError.INVALID_STATE_ERR:
      msg = 'INVALID_STATE_ERR';
      break;
    default:
      msg = 'Unknown Error';
      break;
  };

  console.log('Error: ' + msg);
}

function handleDropEvent (e) {
    // this function handles the file drop...
    if (e.stopPropagation) {
	e.stopPropagation();
    }

    var files = e.dataTransfer.files;
    var output = [];
    for (var i = 0, f; f = files[i]; i++) {

	    (function(file) {
		fs.root.getFile(f.name, {create: true, exclusive: true}, function(fileEntry) {
		    fileEntry.createWriter(function(fileWriter) {
			fileWriter.write(file); // Note: write() can take a File or Blob object.
			console.log('file written');
		    }, errorHandler);
		}, errorHandler);
	    })(f);
	    

 	//fs.root.getFile(f.name, {create: true, exclusive: true}, function(fileEntry) {

        //fileEntry.createWriter(function(fileWriter) {
	//fileWriter.write(f); // Note: write() can take a File or Blob object.
	//console.log('file wrote - hurrah!');
	//}, errorHandler);

	    // fileEntry.isFile === true
	    // fileEntry.name == 'log.txt'
	    // fileEntry.fullPath == '/log.txt'
	    
	//}, errorHandler);

      output.push('<li><strong>', f.name, '</strong> (', f.type || 'n/a', ') - ',
                  f.size, ' bytes, last modified: ',
                  f.lastModifiedDate.toLocaleDateString(), '</li>');
    }

    this.innerHTML += '<p>' + output + '</p>';

    return false;
}

function cancel(e) {
  if (e.preventDefault) {
    e.preventDefault();
  }
  return false;
}

function configurePage() {
    // need to add a handler which figures out what to do when we drop something on the droppable section...
    var drop = document.querySelector('#dropzone');
    
    // Tells the browser that we *can* drop on this target
    addEvent(drop, 'dragover', cancel);
    addEvent(drop, 'dragenter', cancel);
    
    addEvent(drop, 'drop', handleDropEvent ); 

    window.requestFileSystem(window.PERSISTENT, 5*1024*1024,
			     function(filesystem) {
				 fs = filesystem;
				 console.log('filesystem got!');

			     }, errorHandler);
}
